<template>
  <div class="app-container" style="padding:0">
      <div style="margin-top:20px">
        <!--搜索-->
        <el-form :inline="true" :model="listQuery" size="mini" label-width="80px">
          <el-form-item label="产品线：">
            <el-input v-model="listQuery.goodsLine"></el-input>
          </el-form-item>
          <el-form-item label="商品牌号：">
            <el-input v-model="listQuery.goodsSn"></el-input>
          </el-form-item>
          <el-form-item label="负责人：">
            <el-select clearable v-model="listQuery.userId" filterable>
              <el-option
                v-for="item in userOptionList"
                :key="item.userId"
                :label="item.realName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleSearchList" type="primary">查询</el-button>
            <el-button @click="showImport2" type="primary">导入</el-button>
            <el-button @click="showPop('add')" type="primary">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!--数据列表-->
      <div class="table-container">
        <el-table
          v-loading="listLoading"
          :data="tableData"
          border
          style="width: 100%; margin-top: 20px">
          <el-table-column  label="产品线"  align="center" min-width="100">
            <template slot-scope="scope">
                  {{scope.row.goodsLine}}
            </template>
          </el-table-column>
          <el-table-column align="center" label="商品牌号" min-width="100">
            <template slot-scope="scope">
              {{scope.row.goodsSn}}
            </template>
          </el-table-column>
          <el-table-column label="负责人" align="center" min-width="100">
            <template slot-scope="scope">
              {{scope.row.user}}
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            min-width="150"
            label="更新时间">
            <template  slot-scope="scope">
                {{scope.row.updatedAt}}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            width="150"
            label="操作"
            align="center">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="showPop('edit',scope.row)">编辑</el-button>
              <el-button type="text" size="mini" @click="delRow(scope.row)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes,prev, pager, next,jumper"
          :current-page.sync="listQuery.pageNum"
          :page-size="listQuery.pageSize"
          :page-sizes="[10,15,20,50,100]"
          :total="count">
        </el-pagination>
      </div>


    <!--新增商品-->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="420px">
      <el-form :model="form" size="mini" label-width="120px" ref="form" :rules="rules">
        <el-form-item label="产品线：" prop="goodsLine">
            <el-input v-model="form.goodsLine"></el-input>
        </el-form-item>
        <el-form-item label="商品牌号：" prop="goodsSn">
          <el-input v-model="form.goodsSn"></el-input>
        </el-form-item>
        <el-form-item label="负责人：" prop="userId">
           <el-select v-model="form.userId" filterable clearable>
             <el-option
               v-for="item in userOptionList"
               :key="item.userId"
               :label="item.realName"
               :value="item.userId">
             </el-option>
           </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>
    <!--导入-->
    <el-dialog
      :show-close="showClose2"
      :close-on-click-modal="showClose2"
      :close-on-press-escape="showClose2"
      title="商品导入"
      :beforeClose="beforeCloseEditPrice2"
      :visible.sync="dialogVisibleImprot2"
      width="500px">
      <div>
        <el-alert
          title="请先按约定好的字段导入商品"
          type="warning"
          :closable="false">
        </el-alert>
        <div class="upload-div" style="margin-top:20px">
          <input id="upload" type="file" @change="importfxx(this)" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
          <el-button type="primary" size="small" :loading="uploadLoading">选择上传文件</el-button>
        </div>
        <div style="margin:20px auto;margin-bottom:0;word-break:break-all;text-align: left;line-height:20px;background: #fef0f0;color:#f56c6c;padding:10px" v-if="msg2!=''">
          <div style="max-height: 90px;overflow: auto;padding:10px"><div v-if="showFial2">添加失败：</div>{{msg2}}</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleEditPriceConfirm2" :loading="EditLoading2">提 交</el-button>
      </span>
    </el-dialog>


  </div>
</template>
<script>

import {getOrderUsersList, getUserOption} from '@/api/partner'
import {getEditLineSn,getlineSnList,deleteLineSn,exportByLineSn} from '@/api/company'
import {formatDate} from '@/utils/date';
import XLSX from "xlsx";

const defaultListQuery={
  goodsLine: '',
  goodsSn: '',
  userId:'',
  "pageNum" : 1,
  "pageSize" : 10
};
const defaultForm = {
  goodsLine: '',
  goodsSn: '',
  userId:'',
  pgId: 0,
}

export default {
  name: "market",
  data(){
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      tableData: [],
      count: 0,
      listLoading: false,
      keyword:'',
      dialogVisible:false,
      btnLoading:false,
      form:JSON.parse(JSON.stringify(defaultForm)),
      rules:{
        goodsLine : [{required: true, message: '此项必填', trigger: 'blur'},],
        goodsSn:[{required: true, message: '此项必填', trigger: 'blur'},],
        userId:[{required: true, message: '此项必填', trigger: 'change'},],
      },
      popType:'',
      userOptionList:[],

      showClose2:true,
      dialogVisibleImprot2:false,//批量导入弹窗
      EditLoading2:false,//批量导入提交按钮loadin
      showFial2:false,//批量导入失败
      msg2:'',//上传文件信息
      uploadLoading:false,
      da:[],
      file:null,
      title:''
    }
  },

  computed: {

  },
  created() {


  },
  methods:{
    //删除
    delRow(item){
      this.$confirm('确定删除此条记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteLineSn({pgId:item.pgId}).then(()=>{
          this.getList();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    init(){
      this.getUserOptionList()
      this.getList()
    },
    //获取员工下拉选项
    getUserOptionList(){
      getUserOption().then((res)=>{
        this.userOptionList = res;
      })
    },
    showPop(type,item){
      this.popType = type;
      this.dialogVisible = true;
      this.form = JSON.parse(JSON.stringify(defaultForm))
      this.title = '新增商品'
      if(item){
        this.form.pgId = item.pgId;
        this.form.goodsLine = item.goodsLine
        this.form.goodsSn = item.goodsSn
        this.form.userId = item.userId
        this.title = '编辑商品'
      }
    },

    handleConfirm(){

      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          let data = JSON.parse(JSON.stringify(this.form));
          getEditLineSn(data).then((res)=>{
            this.btnLoading = false;
            this.dialogVisible = false;
            this.getList()
          }).catch(()=>{
            this.btnLoading = false;
          })
        }
      });
    },

    handleClose(){
      this.dialogVisible = false
    },

    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getList();
    },

    //获取列表
    getList() {
      this.listLoading = true;
      getlineSnList(this.listQuery).then(response => {
          this.tableData = response.list;
          this.count = response.count;
          this.listLoading = false;
        }).catch(()=>{
          this.listLoading = false;
        });
    },

    //导入excel
    importfxx(obj) {
      let _this = this;
      this.uploadLoading = true;
      let inputDOM = this.$refs.inputer;
      // 通过DOM取文件数据
      this.file = event.currentTarget.files[0];
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;
      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function(f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function(e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for(var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          var XLSX = require('xlsx');
          if(rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), { //手动转化
              type: 'base64'
            });
          } else {
            wb = XLSX.read(binary, {
              type: 'binary'
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);//outdata就是你想要的东西
          // if (outdata.length  > 200){
          //   _this.$message({
          //     message: '最大上传200条',
          //     type: 'error'
          //   });
          //   var test = document.getElementById('upload');
          //   test.value = '';
          //   return false;
          // }
          _this.da = [...outdata];
          console.log("da",_this.da)
          let arr = [];

          let para = {
            withList: arr
          };
          _this.$message({
            message: '上传成功，请点击提交',
            type: 'success'
          });
          _this.uploadLoading = false;
        };
        reader.readAsArrayBuffer(f);
      };
      if(rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },

    //显示导入弹窗
    showImport2(){
      this.showFial2 = false;
      this.EditLoading2 = false;
      this.uploadLoading = false;
      this.msg2 = '';
      this.dialogVisibleImprot2 = true;
    },
    //关闭导入弹窗
    beforeCloseEditPrice2(){
      $("#upload").val('');
      this.da = [];
      this.msg2 = '';
      this.dialogVisibleImprot2 = false;
    },


    //提交导入
    handleEditPriceConfirm2(){
      if (this.da.length == 0){
        this.$message({
          message: '上传数据为空',
          type: 'warning'
        });
        return false;
      }
      this.msg2 = '后台处理中，请耐心等待……';
      this.showFial2 = false;
      this.EditLoading2 = true;
      this.showClose2 = false;
      exportByLineSn({list:this.da}).then((res)=>{
        this.$message({
          message: '修改成功',
          type: 'success'
        });
        this.msg2 = '修改成功';
        this.EditLoading2 = false;
        this.dialogVisible2 = false;
        this.showClose2 = true;
        this.da = [];
        this.dialogVisibleImprot2 = false;
        $("#upload").val('');
        this.getList();
      }).catch((err)=>{
        this.msg2 = err.msg;
        this.showFial2 = true;
        this.EditLoading2 = false;
        $("#upload").val('');
        this.showClose2 = true;
      })
    },
  },
}
</script>


<style scoped lang="scss">
.upload-div{
  text-align: center;
  position:relative;
  #upload{

    opacity: 0;
    position: absolute;
    z-index: 1;
    width:154px;
    height:40px
  }
}
</style>
